package org.shoukaiseki.inittable.handle;

import com.alibaba.fastjson2.JSONObject;
import org.shoukaiseki.inittable.logger.InitTableLoggers;
import org.shoukaiseki.kakaroto.annotation.TableBuild;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Set;

public class TableBuildPackageScanHandle extends ClassPathBeanDefinitionScanner {


    public static final Logger logger = InitTableLoggers.DEFAULT_LOGGER;


    public TableBuildPackageScanHandle(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
        super(registry, useDefaultFilters);
    }


    public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        //添加过滤条件
        addIncludeFilter(new AnnotationTypeFilter(TableBuild.class));
        //调用spring的扫描
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        if(beanDefinitionHolders.size() != 0){
            for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
                if (logger.isDebugEnabled()) {
                    logger.debug("beanDefinitionHolder");
                    try{
                        logger.debug("beanDefinitionHolder={}", JSONObject.toJSONString(beanDefinitionHolder));
                    }catch (Throwable t){
                        try{
                        logger.debug("beanDefinitionHolder={}", beanDefinitionHolder.getBeanName());
                        }catch (Throwable t2){}
                    }
                }
            }
        }
        return beanDefinitionHolders;
    }


    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isIndependent();
    }


}
